﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Devices.Sensors;
using System.Device.Location;

namespace SkyPoint
{

    public class MotionBackend
    {
        Motion motion;
        GeoCoordinateWatcher geoCoordinateWatcher;

        public double Azimuth { get; private set; }
        public double Elevation { get; private set; }

        public double Latitude { get; private set; }
        public double Longitude { get; private set; }

        public MotionBackend()
        {
            motion = new Motion();
            geoCoordinateWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
            

            motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
            motion.CurrentValueChanged += motion_CurrentValueChanged;


            geoCoordinateWatcher.MovementThreshold = 20;
            geoCoordinateWatcher.PositionChanged += geoCoordinateWatcher_PositionChanged;
        }

        public void StartSensors()
        {
            motion.Start();
        }

        public void StopSensors()
        {
            motion.Stop();
        }

        void motion_CurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> e)
        {
            Elevation = (e.SensorReading.Attitude.Pitch * 180 / Math.PI) - 90;
            Azimuth = 360 - (e.SensorReading.Attitude.Yaw * 180 / Math.PI);
        }

        public void UpdatePosition()
        {
            geoCoordinateWatcher.Start();
        }

        private void geoCoordinateWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Latitude = e.Position.Location.Latitude;
            Longitude = e.Position.Location.Longitude;
            geoCoordinateWatcher.Stop();
        }
    }
}
